package com.lovezy.platform.core.email;

import com.lovezy.platform.core.exception.DefaultErrorCode;
import com.lovezy.platform.core.exception.ServiceException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件发送类
 * Created by jin on 2017/11/9.
 */
public class EmailSender {

    private final Log log = LogFactory.getLog(EmailSender.class);

    private JavaMailSender sender;

    private String from;

    @Async
    public void send(@NotNull EmailTarget target) {
        MimeMessage mimeMessage = createMimeMessage();
        buildEmail(mimeMessage, target);
        sender.send(mimeMessage);
    }

    private MimeMessage createMimeMessage() {
        if (sender == null) {
            throw new ServiceException(DefaultErrorCode.SERVICE_ERROR, "邮箱发送者未配置");
        }
        return sender.createMimeMessage();
    }

    private void buildEmail(MimeMessage mimeMessage,EmailTarget target) {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
        if (from == null) {
            throw new ServiceException(DefaultErrorCode.SERVICE_ERROR, "邮箱发送者来源未配置");
        }
        try {
            message.setFrom(from);
            message.setTo(target.getAddress());
            message.setSubject(target.getSubject());
            message.setText(target.getText());
        } catch (MessagingException e) {
            log.error("邮箱发送者来源配置错误", e);
            throw new ServiceException(DefaultErrorCode.SERVICE_ERROR, "邮箱发送者来源未配置");
        }
    }

    @Autowired
    public void setSender(JavaMailSender sender) {
        this.sender = sender;
    }

    @Value("${spring.mail.username}")
    public void setFrom(String from) {
        this.from = from;
    }
}
